<script>
/*
 * @Author: Your name
 * @Date:   2020-08-04 16:33:25
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-08-06 12:02:21
 */
</script>
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="card-box">
      <!-- 添加角色 -->
      <el-button type="primary" @click="addRoles" class="addButton"
        >添加角色</el-button
      >
      <!-- 列表区域 -->
      <el-table :data="rolesList" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- <pre>{{scope.row}}</pre> -->
            <el-row
              :class="[i1 === 0 ? 'bdtop' : '', 'vcenter', 'bdbottom']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightsById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter', 'bdbottom']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightsById(scope.row, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      @close="removeRightsById(scope.row, item3.id)"
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="rolesDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="rolesEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-s-help"
              @click="rolesHelp(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="helpDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        node-key="id"
        default-expand-all
        show-checkbox
        ref="treeRef"
        :default-checked-keys="defKeys"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="helpDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAllotRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色的弹出框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="setAddDialogClosed"
    >
      <el-form :model="roleFormData" ref="addRoleForm" :rules="addRolesRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleFormData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleFormData.roleDesc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doAddRoles">立即创建</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑角色的弹出框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form :model="editRoleFormData" ref="editRoleForm">
        <el-form-item label="角色名称">
          <el-input disabled v-model="editRoleFormData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleFormData.roleDesc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doEditRoles">立即创建</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { request2 } from 'network/request.js'
export default {
  name: 'Roles',
  data() {
    return {
      // 展示的角色数据
      rolesList: [],
      // 添加角色表单数据
      roleFormData: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色表单中的数据
      editRoleFormData: {},
      // 添加角色表单的校验规则
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制分配权限的窗口是否显示
      helpDialogVisible: false,
      // 添加角色信息框的关闭和显示
      addDialogVisible: false,
      // 控制编辑角色的弹出框是否显示
      editDialogVisible: false,
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 所有权限列表
      rightsList: [],
      // 分配权限时的角色id
      roleId: null,
      // 权限列表中默认被选中的权限的数组
      defKeys: []
    }
  },
  methods: {
    // 获取角色数据
    async getRolesList() {
      let res = await request2({
        url: '/roles',
        method: 'get'
      })
      // console.log(res.data)
      if (res.meta.status !== 200) {
        this.$message.error('角色信息获取失败')
        return
      }
      this.rolesList = res.data
    },
    // 删除角色
    rolesDelete(userinfo) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async (then) => {
          let res = await request2({
            method: 'delete',
            url: `/roles/${userinfo.id}`
          })
          // console.log(res)
          if(res.meta.status !== 200) {
            this.$message.error('删除失败')
            return
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getRolesList()
        })
        .catch((error) => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击编辑角色按钮
    rolesEdit(userinfo) {
      this.editDialogVisible = true
      this.editRoleFormData = userinfo
    },
    // 确认提交编辑
    async doEditRoles() {
      let res = await request2({
        url: `/roles/${parseInt(this.editRoleFormData.id)}`,
        method: 'put',
        data: {
          roleName: this.editRoleFormData.roleName,
          roleDesc: this.editRoleFormData.roleDesc
        }
      })
      // console.log(res)
      if(res.meta.status !== 200) {
        this.$message.error('编辑失败')
        return
      }
      this.$message.success('编辑成功')
      this.editDialogVisible = false
    },
    // 点击分配权限按钮事件处理
    async rolesHelp(userinfo) {
      this.helpDialogVisible = true
      // 储存角色id为后面确认分配权限提供参数
      this.roleId = userinfo.id
      // 获取三级节点的id值存储在defkeys中用来显示权限列表中默认被选中的权限
      this.getCheckedNode(userinfo, this.defKeys)
      // 获取所有权限
      let res = await request2({
        url: '/rights/tree',
        method: 'get'
      })
      // console.log('权限列表'+res)
      if (res.meta.status !== 200) {
        this.$message.error('权限列表获取失败')
        return
      }
      this.rightsList = res.data
    },
    // 递归获取到当前角色下所有的权限用来显示权限列表中默认被选中的权限
    getCheckedNode(node, array) {
      if (!node.children) {
        return array.push(node.id)
      }
      node.children.forEach(item => {
        this.getCheckedNode(item, array)
      })
    },
    // 确认分配权限事件处理
    async doAllotRoles() {
      let checkedKeys = this.$refs.treeRef.getCheckedKeys()
      let checkedHelfKeys = this.$refs.treeRef.getHalfCheckedKeys()
      let idArr = [...checkedKeys, ...checkedHelfKeys]
      let idStr = idArr.join(',')
      // console.log('idStr'+idStr)
      let res = await request2({
        url: `/roles/${this.roleId}/rights`,
        method: 'post',
        data: {
          rids: idStr
        }
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('角色分配权限失败')
        return
      }
      this.$message.success('角色分配权限成功')
      this.getRolesList()
      this.helpDialogVisible = false
    },
    // 根据id删除某个权限roles/:roleId/rights/:rightId
    async removeRightsById(userinfo, id) {
      let res = await request2({
        url: `/roles/${userinfo.id}/rights/${id}`,
        method: 'delete'
      })
      if (res.meta.status !== 200) {
        this.$message.error('删除权限失败')
        return
      }
      // console.log(res.data)
      this.$message.success('删除权限成功')
      // 不删除界面实时显示删除后的结果
      userinfo.children = res.data
    },
    // 分配权限弹框关闭的事件处理,并清空默认选中数组中的id
    setRightDialogClosed() {
      this.defKeys = []
      this.helpDialogVisible = false
    },
    // 显示添加角色弹框
    addRoles() {
      this.addDialogVisible = true
    },
    // 添加角色事件处理
    doAddRoles() {
      this.$refs.addRoleForm.validate(async (valid) => {
        if (!valid) return
        let res = await request2({
          url: 'roles',
          method: 'post',
          data: {
            roleName: this.roleFormData.roleName,
            roleDesc: this.roleFormData.roleDesc
          }
        })
        if(res.meta.status !== 201){
          this.$message.error('角色创建失败')
          return
        }
        this.$message.success('角色创建成功')
        this.addDialogVisible = false
        this.getRolesList()
      });
    },
    // 关闭添加角色弹出框
    setAddDialogClosed() {
      this.$refs.addRoleForm.resetFields()
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
.el-card {
  margin-top: 20px;
  .addButton {
    margin-bottom: 20px;
  }
}
</style>
